package snu.bi.MSAgent;

import java.math.BigDecimal;
import java.util.ArrayList;

import snu.bi.MSAgent.DB.MSADBHandler;
import snu.bi.MSAgent.menuHN.HN;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MenuActivity extends Activity {
	Button ok;
	ListView lv;
	TextView total_cal;
	HN hn;
	boolean learning;
	//String dbpath;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.recom_menu_lay);		
		
		ok = (Button)findViewById(R.id.recom_menu_ok);
		total_cal = (TextView)findViewById(R.id.recom_menu_cal_value);
		lv = (ListView)findViewById(R.id.recom_menu_lists);
		hn = new HN(this.getApplicationContext());
		
		learning = false;
		if(hn.needlearning()) {
			learning = true;
			Toast.makeText(this, "learning... It can take some minutes", Toast.LENGTH_SHORT).show();
			Thread thr = hnlearning(this);
			thr.run();
			learning = false;
		}
		
		paint(recom_menu(), lv, total_cal);
		/*
		String items[] = recom_menu();
		ArrayAdapter <String> aa = new ArrayAdapter <String> (this, android.R.layout.simple_list_item_1, items);
		lv.setAdapter(aa);
		*/
		//returnback(ok);		
	}	
	public void returnback(View view) {
		finish();
	}
	public int[] recom_menu() {
		//menu �� _id = 1 �� �˻��ص� ��� ������ ����
		/*
		HN hn = new HN(this.getApplicationContext());
		hn.learning();
		int result[] = hn.make_menu(850);
		*/
		int result[];
		if(learning) {
			result = new int[5];
			return result;
		}
		else {
			result = hn.make_menu(850);		
		}
		return result;
	}
	public void paint(int[] items, ListView lv, TextView tv) {
		double temp_cal = 0;
		ArrayList<menu_item> mlist = new ArrayList<menu_item>();
		
		MSADBHandler thisdb = MSADBHandler.open(this.getApplicationContext());		
		for(int i=0; i<items.length; i++) {
			//mlist.add(new menu_item(thisdb.rawQuery("select * from menu where _id="+items[i], null)));			
			Cursor c = thisdb.rawQuery("select * from menu where _id="+items[i]);
			if(c.getCount() != 0) mlist.add(new menu_item(c));
			c.close();
		}
		thisdb.close();
		
		for(int i=0; i<mlist.size(); i++) temp_cal += mlist.get(i).cal;
		
		menuAdapter mA = new menuAdapter(this, R.layout.menu_item_row, mlist);
		lv.setAdapter(mA);
		tv.setText(Double.toString(Math.round(temp_cal*100)/100)+" kcal");
	}
	private Thread hnlearning(Activity act) {
    	//http://hyeongkyu.net/110090943249
    	//�޾� ���� �ð��� ���� �ɸ� �� �ֱ� ������ thread�� �ؾ��Ѵ�
    	Thread thr = new Thread(new Runnable() {
			public void run() {
				hn.learning();
			}
    	});    	
    	return thr;
	}
}
